package com.oncecloud.devops.client.ldap;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.oncecloud.devops.client.constant.Status;
import com.oncecloud.devops.client.constant.Status.LOGIN_STATUS;
import com.oncecloud.devops.client.entity.User;
import com.oncecloud.devops.client.service.UserService;
import com.oncecloud.devops.client.util.HashUtil;

@Component
@PropertySource("classpath:config/scheduled.properties")
public class LdapSyncJob{
	private Logger logger = Logger.getLogger(this.getClass());
	private LdapAnon ldapAnon = Factory.createAnonInstance();
	ConfigureCommon cfg = new ConfigureCommon("config/ldap.properties");
	private String LDAPEnable = cfg.getKey("ldap.enable"); //true 使用ldap,false不使用ldap
	private  static boolean ldapSyncIsDoing=false;
	@Resource
	private UserService userService;
	
	@Scheduled(cron="${jobs.schedule}") 
	public void ldapSyncUser() {
		 try {
			 if(ldapSyncIsDoing==false){
				 User user=null;
				 ldapSyncIsDoing=true;//标志正在执行同步任务
				 if("false".equalsIgnoreCase(LDAPEnable)){
						return;
				}
				 ldapAnon.connect();
				 List<User> userList=ldapAnon.searchAll();
				 logger.info("ldap synchronization strat ");
				 for (int i = 0; i < userList.size(); i++) {
					 logger.info(">>>>>"+userList.get(i).getLdapUid()+"["+userList.get(i).getUserName()+"]");
					 user=userService.getUserByUid(userList.get(i).getLdapUid().toString());
					 User ldapUser=new User();
					 if (user == null) {
						 ldapUser.setLdapUid(userList.get(i).getLdapUid());
						 ldapUser.setUserName(userList.get(i).getLdapUid());
						 ldapUser.setUserMail(userList.get(i).getUserMail());
						 ldapUser.setUserStatus((byte) Status.USER.NORMAL.ordinal());
						 //ldapUser.setUserLevel(1);
						 ldapUser.setUserPass(userList.get(i).getUserPass()==null?HashUtil.md5Hash("123456"):userList.get(i).getUserPass());
						 ldapUser.setUserCreator(1);
						 ldapUser.setUserCreatedate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
						 ldapUser.setLoginStatus((byte)LOGIN_STATUS.OFF.ordinal());
						 userService.insert(ldapUser);
						 logger.info(userList.get(i).getLdapUid()+" synchronization completed.");
					 }else {
						 if(userList.get(i).getUserPass()!=null){
							 if(!userList.get(i).getUserPass().equals(user.getUserPass())){
								 ldapUser.setUserPass(userList.get(i).getUserPass()==null?HashUtil.md5Hash("123456"):userList.get(i).getUserPass());
								 userService.updateByUid(ldapUser);
								 logger.info(userList.get(i).getLdapUid()+" already exist. but password is updated.");
							 }else {
								 logger.info(userList.get(i).getLdapUid()+" already exist.");
							 }
						 }
					 }
				 }
				 logger.info("ldap synchronization completed");
			 }
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			ldapSyncIsDoing=false;
			ldapAnon.close();
		}
	}
       
	
}
